<template>
  <div id="main"></div>
</template>

<script setup>
import { getMapDataApi } from '@/api/system/conf'
import getOption from '@/utils/echarts/mapOptionUtil'

const xzqhNow = reactive({
  code: '3706',
  name: '烟台市',
})

let mapChart = null

// 更新geoJSON
const readJsonFile = (url) => {
  return new Promise((resolve, reject) => {
    getMapDataApi(url)
      .then((res) => {
        let colorNum = 15 // 15种颜色
        let v = 0
        let data = res.features.map((i, index) => {
          v = v < colorNum ? v + 1 : 1
          return {
            name: i.properties.name,
            code: i.properties.code,
            value: v,
          }
        })
        resolve({
          geoJSON: res, // 地图json数据
          mapData: data, // 点击地图获取的数据
        })
        mapChart.hideLoading()
      })
      .catch((err) => {
        console.log(err)
        console.log('文件读取失败:: ', url)
        mapChart.hideLoading()
      })
  })
}

// 地图loading
const showMapLoading = () => {
  mapChart.showLoading({
    text: 'loading',
    color: '#c23531',
    textColor: '#000',
    maskColor: 'rgba(255, 255, 255, 0.8)',
    zlevel: 100,
    fontSize: 12,
    showSpinner: true,
    spinnerRadius: 10,
    lineWidth: 5,
  })
}

// 渲染map
function renderMap() {
  showMapLoading()
  let mapUrl = `${xzqhNow.name}.json`

  readJsonFile(mapUrl).then(function (res) {
    let geoJSON = res.geoJSON // 地图元素geo数据
    let mapData = res.mapData // 地图点击数据

    echarts.registerMap(xzqhNow.name, geoJSON)
    const mapOption = getOption(xzqhNow.name, mapData, xzqhNow.code)
    mapChart.setOption(mapOption, true)
  })
}

nextTick(() => {
  mapChart = echarts.init(document.getElementById('main'))
  mapChart.clear()

  renderMap()

  mapChart.on('click', (params) => {
    console.log(params)
    // 点击地图导航
    if (params.componentType === 'graphic') {
      if (params.info) {
        xzqhNow.name = params.info.name
        xzqhNow.code = params.info.code
      }
    }
    // 点击地图块
    if (params.componentType === 'series') {
      xzqhNow.name = params.data.name
      xzqhNow.code = params.data.code
    }
    renderMap()
  })
})
</script>

<style scoped>
#main {
  margin: 0 auto;
  width: 100%;
  height: 100%;
  background-color: #fff;
}
</style>
